package com.baichang.taoshunda.service.impl;

import com.alipay.api.AppPay;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.KidUtils;
import com.baichang.framework.utils.LogUtils;
import com.baichang.taoshunda.dao.BussinessDao;
import com.baichang.taoshunda.dao.CarouselDao;
import com.baichang.taoshunda.dao.CompanyPanymentHistoryDao;
import com.baichang.taoshunda.dao.RecommendCompanyDao;
import com.baichang.taoshunda.entity.Bussiness;
import com.baichang.taoshunda.entity.Carousel;
import com.baichang.taoshunda.entity.CompanyPanymentHistory;
import com.baichang.taoshunda.entity.RecommendCompany;
import com.baichang.taoshunda.entity.em.currencyCode;
import com.baichang.taoshunda.entity.em.payHistory;
import com.baichang.taoshunda.service.CarouselService;
import com.weixin.pay.api.WeixinPay;
import com.weixin.pay.api.model.PayInfo;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ${wushenglu} on 2017/8/18 0018.
 */
@Service
public class CarouselServiceImpl implements CarouselService {
    @Autowired
    private CarouselDao carouselDao;

    @Autowired
    private BussinessDao bussinessDao;

    @Autowired
    private CompanyPanymentHistoryDao companyPanymentHistoryDao;

    @Autowired
    private RecommendCompanyDao recommendCompanyDao;

    /**
     * 根据城市获取首页轮播图
     *
     * @param areaId 城市编号
     * @param type
     * @param lat
     * @param lng    @return
     */
    @Override
    public List<Map<String, Object>> getCarouselByCity(Integer areaId, Integer type, String lat, String lng) {
        return carouselDao.getCarouselByCity(areaId, type, lat, lng);
    }

    /**
     * 修改商家推荐轮播图
     *
     * @param id
     * @param link
     * @return
     */
    @Override
    public int updateCarousel(Integer id, Integer link) {
        //修改轮播图状态
        carouselDao.updateStatus(id);
        //删除当前轮播图的缴费记录
        companyPanymentHistoryDao.deleteCode(id);
        return bussinessDao.updateBusState(link);
    }

    /**
     * 修改排名
     *
     * @param id
     * @param orderNum
     * @param sorting
     * @return
     */
    @Override
    public int updateOrderNum(Integer id, Integer orderNum, Integer sorting) {
        if (sorting == 0) {
            carouselDao.updateOrderNum(id, orderNum);
        } else {
            bussinessDao.updateSorting(id, sorting);
        }
        return 0;
    }

    /**
     * 申请广告位
     *
     * @param
     * @param
     * @param
     * @param busId 商家编号
     * @param type  申请类型
     * @return
     */
    @Override
    public Map<String, Object> addCarousel(Integer busId, Integer type) throws ServiceException {
        if (type == 1) {
            int linkType = 1;
            Map<String, Object> maps = carouselDao.queryBusCarousel(busId, linkType);
            if (maps != null) {
                throw new ServiceException("您申请的广告位正在展示，不能再申请");
            }
            Bussiness business = bussinessDao.getEntityById(busId);
            Carousel carousel = new Carousel();
            carousel.setCityId(business.getCityId());
            carousel.setStatus(1);
            carousel.setCreated(new Date());
            carousel.setLink(busId.toString());
            carousel.setOrderNum(0);
            carousel.setPass(currencyCode.待支付.getCode());
            carousel.setLat(business.getLat());
            carousel.setLng(business.getLng());
            carousel.setAreaId(business.getAreaId());
            //首页广告位
            carousel.setLinkType(1);
            carouselDao.save(carousel);
            //查询最新创建的数据id
            Map<String, Object> map = carouselDao.queryCarouselId();
//        String carouselId = map.get("id").toString();
//        int payId = Integer.parseInt(carouselId);
            return map;
        } else {
            //查询待支付、审核中的推荐诚信商家 状态为1和4
            //审核通过的不用进行查询，手机端不让申请
            Map<String, Object> mapNum = recommendCompanyDao.getAuditRecommentdBusiness(busId);
            /**
             * 如果不等于0，则进行异常返回
             */
            String recommendNum = mapNum.get("num").toString();
            if (!recommendNum.equals("0")) {
                throw new ServiceException("该商家已申请推荐诚信商家，不能在申请");
            }
            Map<String, Object> maps = recommendCompanyDao.queryRecommendBus(busId);
            if (maps != null) {
                throw new ServiceException("您申请的推荐商家正在展示，不能再申请");
            }
            Bussiness business = bussinessDao.getEntityById(busId);
            RecommendCompany recommendCompany = new RecommendCompany();
            recommendCompany.setAuditingStatus(currencyCode.待支付.getCode());
            recommendCompany.setStatus(1);
            recommendCompany.setCompanyId(busId);
            recommendCompany.setNumber(0);
            recommendCompany.setCreatedTime(new Date());
            recommendCompany.setLng(business.getLng());
            recommendCompany.setLat(business.getLat());
            recommendCompany.setCityId(business.getCityId());
            recommendCompany.setAreaId(business.getAreaId());
            recommendCompanyDao.save(recommendCompany);
            //查询最新创建的数据id
            Map<String, Object> map = recommendCompanyDao.queryInfoId();
            return map;
        }
    }

    /**
     * 查询需要审核的广告位
     *
     * @param businessName
     * @param type
     * @param nowPage
     * @param pageSize     @return
     */
    @Override
    public Page queryAuditingCarosuel(String businessName, Integer type, int nowPage, int pageSize) {
        return carouselDao.queryAuditingCarosuel(businessName, type, nowPage, pageSize);
    }

    /**
     * 轮播图上传图片
     *
     * @param id
     * @param picture
     * @param
     * @return
     */
    @Override
    public int addPicture(Integer id, String picture) {
        Map<String, Object> map = companyPanymentHistoryDao.getHistoryInfo(id);
        String num = map.get("paymentTime").toString();
        int month = Integer.parseInt(num);
        //系统时间
        Date time = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, month);
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //系统时间  ---开始时间
        String startTime = dft.format(time.getTime());
        //系统时间+月份 ---结束时间
        String endTime = dft.format(cal.getTime());
        return carouselDao.addPicture(id, picture, currencyCode.同意申请.getCode(), startTime, endTime);
    }

    /**
     * 审核拒绝
     *
     * @param id
     * @return
     */
    @Override
    public int update(Integer id) {
        return carouselDao.updatePass(id, currencyCode.拒绝申请.getCode());
    }


    /**
     * 服务商家支付
     *
     * @param id
     * @param busId
     * @param payType
     * @param money   @return
     * @param status
     */
    @Override
    public Map<String, Object> payMentMoney(Integer id, Integer busId, Integer payType, BigDecimal money, Integer status) {
        System.out.println("请求时间" + new Date() + "id" + id + "busId" + busId + "payType" + payType + "money" + money + "status" + status);
        LogUtils.getInstance().info("请求时间" + new Date() + "id" + id + "busId" + busId + "payType" + payType + "money" + money + "status" + status);
        if (status == 4 || status == 5) {
            String kid = KidUtils.getKKid();
            Map map = new HashedMap();
            Bussiness business = bussinessDao.getEntityById(busId);
            String title = business.getBussName() + "付款：" + money + "元";
            boolean isTrue = false;
            //1支付宝、2微信
            if (payType == 1) {
                //支付宝
                //这里传的是支付订单编号
                String aplipay = AppPay.createPay(title, kid, title, money.doubleValue());
                map.put("pay", aplipay);
            } else if (payType == 2) {
                int price = money.multiply(BigDecimal.valueOf(100)).intValue();
                WeixinPay weixinPay = new com.weixin.pay.api.AppPay();
                PayInfo payInfo = new PayInfo();
                payInfo.setBody(title);
                payInfo.setTradeNo(kid);
                payInfo.setSubject(title);
                payInfo.setPrice(price);
                payInfo.loadWxConfig("wx48217cb07b14d413");
                weixinPay.setPayInfo(payInfo);
                map = weixinPay.createPay();
            }
            System.out.println("3和4的支付信息" + map);
            return map;
        } else {
            String kid = KidUtils.getKKid();
            Map map = new HashedMap();
            Bussiness business = bussinessDao.getEntityById(busId);
            String title = business.getBussName() + "付款：" + money + "元";
            boolean isTrue = false;
            //1支付宝、2微信
            if (payType == 1) {
                //支付宝
                //这里传的是支付订单编号
                String aplipay = AppPay.createPay(title, kid, title, money.doubleValue());
                map.put("pay", aplipay);
            } else if (payType == 2) {
                int price = money.multiply(BigDecimal.valueOf(100)).intValue();
                WeixinPay weixinPay = new com.weixin.pay.api.AppPay();
                PayInfo payInfo = new PayInfo();
                payInfo.setBody(title);
                payInfo.setTradeNo(kid);
                payInfo.setSubject(title);
                payInfo.setPrice(price);
                payInfo.loadWxConfig("wx48217cb07b14d413");
                weixinPay.setPayInfo(payInfo);
                map = weixinPay.createPay();
                System.out.println("支付信息:" + map.toString());
            }
            return map;
        }
    }

    /**
     * 轮播图缴费成功调用
     *
     * @param
     * @param id
     * @param busId
     * @param payType
     * @param money
     * @param month
     * @param type
     * @return
     */
    @Override
    public boolean successPaymentMoney(Integer id, Integer busId, Integer payType, BigDecimal money, Integer month, Integer type) {
        if (type == 1) {
            //修改状态
            carouselDao.updatePass(id, currencyCode.申核中.getCode());
            //轮播图的交易记录
            CompanyPanymentHistory companyPanymentHistory = new CompanyPanymentHistory();
            companyPanymentHistory.setCompanyId(busId);
            companyPanymentHistory.setPaymentMoney(money);
            companyPanymentHistory.setPaymentTime(month);
            companyPanymentHistory.setPaymentType(payHistory.广告位.getCode());
            companyPanymentHistory.setCreatedTime(new Date());
            companyPanymentHistory.setCarouselId(id);
            companyPanymentHistory.setPayType(payType);
            companyPanymentHistory.setWaiterServiceId(0);
            companyPanymentHistory.setGoodId(0);
            return companyPanymentHistoryDao.save(companyPanymentHistory) > 0;
        } else {
            //修改状态
            recommendCompanyDao.updateStaus(id, currencyCode.申核中.getCode());
            //轮播图的交易记录
            CompanyPanymentHistory companyPanymentHistory = new CompanyPanymentHistory();
            companyPanymentHistory.setCompanyId(busId);
            companyPanymentHistory.setPaymentMoney(money);
            companyPanymentHistory.setPaymentTime(month);
            companyPanymentHistory.setPaymentType(payHistory.诚信商家.getCode());
            companyPanymentHistory.setCreatedTime(new Date());
            companyPanymentHistory.setRecommendId(id);
            companyPanymentHistory.setPayType(payType);
            companyPanymentHistory.setWaiterServiceId(0);
            companyPanymentHistory.setCarouselId(0);
            companyPanymentHistory.setGoodId(0);
            return companyPanymentHistoryDao.save(companyPanymentHistory) > 0;
        }
    }

    /**
     * 查询我的轮播图
     *
     * @param busId
     * @param type
     * @return
     */
    @Override
    public Map<String, Object> queryBusCarouselDetails(Integer busId, Integer type) throws ParseException {
        Map<String, Object> map = new HashedMap();
        //查询当前商家的申请     首页  红包  的状态
        List<Map<String, Object>> mapTime = carouselDao.queryCarouselTime(busId, type);
        //判断这个商家  有没有申请当前类型的数据
        if (mapTime == null) {
            map.put("judge", "false");
            return map;
        } else {
            for (int i = 0; i < mapTime.size(); i++) {
                String id = mapTime.get(i).get("id").toString();
                //先判断时间是不是为空
                String time = mapTime.get(i).get("endTime").toString();
                if (!time.equals("0")) {
                    //设置日期格式
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //结束时间
                    Date endTime = df.parse(time);
                    //当前时间
                    String createTime = df.format(new Date());
                    Date data = df.parse(createTime);
                    //结束时间在前  结束时间小于当前时间  -1   结束时间大于当前时间为1   等于为0
                    int a = endTime.compareTo(data);
                    if (a == -1) {
                        //结束时间小于当前时间 修改状态为0
                        //carouselDao.updateStatus(Integer.valueOf(id));
                        map.put("judge", "false");
                    } else {
                        //返回的是展示中并且在结束时间内的
                        map = carouselDao.queryBusCarouselDetails(id);
                        map.put("judge", "true");
                    }
                } else {
                    //返回的是待审核和待支付的
                    map = carouselDao.queryBusCarouselDetails(id);
                    map.put("judge", "true");
                }
            }
        }
        return map;
    }

    /**
     * 查询同意和拒绝的轮播图
     *
     * @param name
     * @param cityId
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page queryCarousel(String name, Integer cityId, Integer type, int nowPage, int pageSize) {
        return carouselDao.queryCarousel(name, cityId, type, nowPage, pageSize);
    }

    /**
     * 更换图片
     *
     * @param id
     * @param picture
     * @return
     */
    @Override
    public int replacePicture(Integer id, String picture) {
        return carouselDao.replacePicture(id, picture);
    }

    /**
     * 添加红包轮播图
     *
     * @param busId
     * @return
     */
    @Override
    public Map<String, Object> addRedCarousel(Integer busId) throws ServiceException {
        int type = 2;
        Map<String, Object> maps = carouselDao.queryBusCarousel(busId, type);
        if (maps != null) {
            throw new ServiceException("您申请的红包广告位正在申请中，不能再申请");
        }
        Bussiness business = bussinessDao.getEntityById(busId);
        Carousel carousel = new Carousel();
        carousel.setCityId(business.getCityId());
        carousel.setStatus(1);
        carousel.setCreated(new Date());
        carousel.setLink(busId.toString());
        carousel.setOrderNum(0);
        carousel.setPass(currencyCode.待支付.getCode());
        carousel.setLat(business.getLat());
        carousel.setLng(business.getLng());
        carousel.setAreaId(business.getAreaId());
        carousel.setLinkType(2); //红包广告位
        carouselDao.save(carousel);
        Map<String, Object> map = carouselDao.queryCarouselId();
        return map;
    }

    /**
     * 查询全部的过往记录
     *
     * @param busId
     * @param type
     * @return
     */
    @Override
    public List<Map<String, Object>> queryAllHistory(Integer busId, Integer type) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (type == 1) {
            list = carouselDao.queryAllHistory(busId, type);
        } else if (type == 2) {
            list = carouselDao.queryAllHistory(busId, type);
        } else if (type == 3) {
            list = recommendCompanyDao.queryAllHistory(busId);
        }
        return list;
    }
}
